package handel

import (
	"821/golab"
	"821/internal/dao"
	"821/internal/model"
	req2 "821/internal/req"
	"821/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
)

func User(c *gin.Context) {
	var req req2.UserReq
	err := c.ShouldBind(&req)
	if err != nil {
		return
	}
	var user model.User
	err = dao.UserFind(user, req.Name)
	token, _ := pkg.TokenHandler(int(user.ID))

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "登录失败",
			"data": nil,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": token,
		})
	}
}
func Chat(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("user_id"))
	conn, err := golab.Upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := golab.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	golab.ClitMap[userId] = node
	go ReadMessage(node)
	go WriteMessage(node)
}
func ReadMessage(node golab.Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			return
		}
		var msg golab.Msg
		err = json.Unmarshal(message, &msg)
		if err != nil {
			return
		}
		golab.ClitMap[msg.DistId].Data <- message
	}
}
func WriteMessage(node golab.Node) {
	for {
		Data := <-node.Data
		node.Conn.WriteMessage(websocket.TextMessage, Data)
	}
}
func List(c *gin.Context) {
	var req req2.ListReq
	err := c.ShouldBind(&req)
	if err != nil {
		return
	}
	var friend model.Friend
	err = dao.UserList(&friend, req.UserId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "展示失败",
			"data": nil,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "展示成功",
			"data": friend,
		})
	}
}
